package novel.util;

import novel.enums.NovelSpiderEnum;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.util.*;

/**
 * @Author:xdw
 * @Date:Created in 下午 5:222019/3/7 0007
 * @described:
 * @Modified By:
 */
public final class NovelSpiderUtil {

    private static final Map<NovelSpiderEnum, Map<String, String>> CONTEXT_MAP = new HashMap<>();

    static {
        init();
    }

    private NovelSpiderUtil() {
    }

    /**
     * 解析spider-Rule.xml,将每个网站的规则存放到CONTEXT_MAP中
     */
    private static void init() {
        SAXReader reader = new SAXReader();
        InputStream in = NovelSpiderUtil.class.getClassLoader().getResourceAsStream("config/spider-Rule.xml");
        try {
            Document doc = reader.read(in);
            //获取根节点
            Element root = doc.getRootElement();

            //获取全部的site节点
            List<Element> sites = root.elements("site");
            for (Element site : sites) {
                //获取site下的全部子节点
                List<Element> subs = site.elements();
                Map<String, String> subMap = new HashMap<>();
                for (Element sub : subs) {
                    String name = sub.getName();
                    String text = sub.getTextTrim();
                    subMap.put(name, text);
                }
                CONTEXT_MAP.put(NovelSpiderEnum.getEnumByUrl(subMap.get("url")), subMap);

            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取对应的网站解析规则
     *
     * @param novelSpiderEnum
     * @return
     */
    public static Map<String, String> getContext(NovelSpiderEnum novelSpiderEnum) {
        return CONTEXT_MAP.get(novelSpiderEnum);
    }


    /**
     * 多个文件合并为一个文件，合并规则：按文件名分割排序
     *
     * @param path        基础目录，该根目录下的所有文本文件都会被合并到 mergeToFile
     * @param mergeToFile 被合并的文本文件，这个参数可以为null,合并后的文件保存在path/merge.txt
     */
    public static void multiFileMerge(String path, String mergeToFile, boolean deleteThisFile) {
        mergeToFile = mergeToFile == null ? path + "/merge.txt" : mergeToFile;
        File[] files = new File(path).listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".txt");
            }
        });
        Arrays.sort(files, new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                int o1Index = Integer.parseInt(o1.getName().split("\\-")[0]);
                int o2Index = Integer.parseInt(o2.getName().split("\\-")[0]);
                if (o1Index > o2Index) {
                    return 1;
                } else if (o1Index == o2Index) {
                    return 0;
                } else {
                    return -1;
                }
            }
        });
        PrintWriter out = null;
        try {
            out = new PrintWriter(new File(mergeToFile), "UTF-8");
            for (File file : files) {
                BufferedReader bufr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
                String line = null;
                while ((line = bufr.readLine()) != null) {
                    out.println(line);
                }
                bufr.close();

                if (deleteThisFile) {
                    file.delete();
                }
            }
        } catch (IOException e1) {
            throw new RuntimeException(e1);
        } finally {
            out.close();
        }
    }
}
